package com.example.l2p_feedback;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class ApiCall extends AsyncTask<String, Void, String> {
	Context context;

	public ApiCall(Context c) {
		this.context = c;
	}

	private String httpCall(Boolean getOrPost, String apiUrl, String apiParams) {
		String fetchedData = "";
		try {
			URL url = new URL(apiUrl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			if (getOrPost) {
				connection.setRequestMethod("GET");
				apiParams = "";
			} else {
				connection.setRequestMethod("POST");
				connection.setRequestProperty("Content-Type",
						"application/x-www-form-urlencoded");
				connection.setRequestProperty("charset", "utf-8");
				connection.setRequestProperty("Content-Length",
						"" + Integer.toString(apiParams.getBytes().length));
				connection.setUseCaches(false);
				DataOutputStream wr = new DataOutputStream(
						connection.getOutputStream());
				wr.writeBytes(apiParams);
				wr.flush();
				wr.close();
			}
			BufferedReader reader = null;
			reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String line = "";
			while ((line = reader.readLine()) != null) {
				// System.out.println(line);
				fetchedData += line;
			}
			reader.close();
			connection.disconnect();
		} catch (Exception e) {
			Log.e("L2P API CALL", e.getMessage());
		}
		return fetchedData;
	}

	/*
	 * private String GET(String url) { String result = ""; try { String
	 * divertUrl = "http://seoul.freehostia.com/divert.php?whichUrl=" +
	 * URLEncoder.encode(url, "UTF-8");
	 * 
	 * HttpClient httpclient = new DefaultHttpClient(); HttpPost http = new
	 * HttpPost(divertUrl);
	 * 
	 * HttpGet httpget = new HttpGet(divertUrl); HttpResponse response; response
	 * = httpclient.execute(httpget); HttpEntity entity = response.getEntity();
	 * if (entity != null) { InputStream instream = entity.getContent(); result
	 * = convertStreamToString(instream); instream.close(); } } catch (Exception
	 * e) { // I don't care now...Later obviously Log.e("L2P API GET",
	 * e.getMessage()); } return result; }
	 */
	@Override
	protected String doInBackground(String... params) {
		String result = "";
		if (!params[0].equalsIgnoreCase("get")
				&& !params[0].equalsIgnoreCase("post")) {
			result = "{'Status':false, 'errorDescription':'Invalid operation type provided. Only GET/POST are supported. You provided: '"
					+ params[0] + "}";
			return result;
		}
		Boolean getOrPost = params[0].equalsIgnoreCase("get");

		if (getOrPost) {
			String divertUrl;
			try {
				divertUrl = "http://seoul.freehostia.com/divert.php?whichUrl="
						+ URLEncoder.encode(params[1], "UTF-8");
				result = this.httpCall(true, divertUrl, null);
			} catch (Exception e) {
				// who cares?
			}
		} else {
			result = this.httpCall(false, params[1], params[2]);
		}
		return result;
	}

	/*
	 * private String convertStreamToString(InputStream is) { BufferedReader
	 * reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb
	 * = new StringBuilder();
	 * 
	 * String line = null; try { while ((line = reader.readLine()) != null) {
	 * sb.append(line + "\n"); } } catch (IOException e) { e.printStackTrace();
	 * } finally { try { is.close(); } catch (IOException e) {
	 * e.printStackTrace(); } }
	 * 
	 * return sb.toString(); }
	 */
	@Override
	protected void onPostExecute(String result) {
		if (result == "") {
			return;
		}
		JSONObject jsonObject;
		try {
			jsonObject = new JSONObject(result);
			Boolean status = jsonObject.getBoolean("Status");
			if (status) {
				// Show response
				Toast.makeText(context, "Response from L2P: " + result,
						Toast.LENGTH_LONG).show();
			} else {
				String errorString= jsonObject.getString("errorDescription");
				Toast.makeText(context, "Error: " + errorString,
						Toast.LENGTH_LONG).show();
				throw new Exception(errorString);
			}
		} catch (Exception e) {
			Log.e("L2P ApiCall onPostExecute", e.getMessage());
		}
	}
}
